// context.arc(unit * 190, unit * 60, unit * 25, 0, 2 * Math.PI) //圆的周长与直径之比 π ，绘制一个圆形
const util = require('../../utils/util.js')
const rate = wx.getSystemInfoSync().windowWidth / 750
const wh = {
  imageItemW: 268,
  marginTop: 159,
  marginLeft: 114,
  fontTop: 460,
  moneyTop: 525,
  leftInterval: 0,
  nameInterval: 22,
  toptInterval: 0,
  fontNum: 10,
  makeMoney: 210,
  fontSize: 22,
  zhuan: true
}

function getImageInfo(url) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: url,
      success: resolve,
      fail: reject,
    })
  })
}

function canvasToTempFilePath(option, context) {
  return new Promise((resolve, reject) => {
    wx.canvasToTempFilePath({
      ...option,
      success: function(res) {
        resolve(res)
        getApp().globalData.shareimage = res
      },
      fail: reject,
    }, context)
  })
}

function saveImageToPhotosAlbum(option, pagethis) {
  var that = this
  return new Promise((resolve, reject) => {
    if (!option.filePath) {
      wx.showToast({
        title: '生成图片中,请稍等',
        icon: 'none',
        duration: 3000,
      })
      reject(false)
      return
    }
    wx.saveImageToPhotosAlbum({
      ...option,
      success: resolve,
      fail: function(res) {
        // pagethis.triggerEvent('myevent', {
        //   'permissionSetting': {
        //     save: false,
        //     setingOn: true
        //   }
        // })
        pagethis.setData({
          'permissionSetting.save': false ,
          'permissionSetting.setingOn': true 
        })
      }
    })
  })
}
Component({
  observers: {
    'showPhoto': function(showPhoto) {
      if (showPhoto) {
        this.draw()
      }
    },
    'permissionSetting': function(permissionSetting) {
      this.data.permissionSetting.data = permissionSetting.data
    },
  },
  properties: {
    showPhoto: {
      type: Boolean,
      value: false,
    },

    permissionSetting: {
      type: Object
    },
    authorization: {
      type: Object,
      value: false,
      observer: function(e) {}
    }
  },
  data: {
    windowWidth: 496 * rate,
    windowHeight: 882 * rate,
    imageFile: '',
    album: "",
    imgUrl: getApp().globalData.imgUrl,
    imgUrls: getApp().globalData.imgUrls,
  },
  lifetimes: {
    ready() {

    },
  },
  methods: {
    previewImage: function (e) {
      var current = e.target.dataset.src;
      var that = this
      wx.previewImage({
        current, // 当前显示图片的http链接
        urls: [current]
      })
   
   
    },
    forEachArr() {
      return new Promise((resolve, reject) => {
        // 处理名字长度
        var that = this
        var data = this.data.permissionSetting.data

        if (data.length > 6) {
          data = data.slice(0, 6)
        }
        data.forEach((item, index) => {
          var nameArr = []
          var nameLength = data[index].goods_name;
          if (item.goods_cover.indexOf(",") != -1) {
            item.goods_cover = item.goods_cover.split(',')[0]
          }
          data[index].goods_cover = getApp().globalData.imgUrls + item.goods_cover;
          if (data.length == 2) {
            wh.imageItemW = 224;
            wh.marginLeft = 19;
            wh.fontNum = 9;
            wh.fontTop = 420;
            wh.moneyTop = 476;
            wh.makeMoney = 100;
            wh.leftInterval = 234;
            wh.nameInterval = 10,
              wh.zhuan = true
          }
          if (data.length == 1) {
              wh.imageItemW= 268,
                wh.marginTop= 159,
                wh.marginLeft= 114,
                wh.fontTop= 460,
                wh.moneyTop= 525,
                wh.leftInterval= 0,
                wh.nameInterval= 22,
                wh.toptInterval= 0,
                wh.fontNum= 10,
                wh.makeMoney= 210,
                wh.fontSize= 22,
                wh.zhuan= true
           
          }
          if (data.length == 1 || data.length == 2) {

            var fontNum = wh.fontNum
            if (nameLength.length <= fontNum) {
              nameArr.push(nameLength)
            } else {
              nameArr.push(nameLength.slice(0, fontNum))
              if (nameLength.length > fontNum * 2 - 1) {
                nameArr.push(nameLength.slice(fontNum, fontNum * 2 - 1) + "...")
              } else {
                nameArr.push(nameLength.slice(fontNum, fontNum * 2 - 1))
              }
            }
          }
          if (data.length > 2) {
            wh.imageItemW = 125;
            wh.marginLeft = 50;
            wh.fontTop = 310;
            wh.moneyTop = 340;
            wh.makeMoney = 120;
            wh.leftInterval = 133;
            wh.nameInterval = 10
            wh.toptInterval = 206;
            wh.fontSize = 17;
            wh.zhuan = false;
            nameLength.length > 6 ? nameLength = nameLength.slice(0, 6) + "..." : ''
            nameArr.push(nameLength)
          }
          data[index].wh = wh
          data[index].goods_name = nameArr
        })
        resolve(data)
      })
    },
    handleClose() {
      this.setData({
        showPhoto: false
      })
    },
    openSetting() {
      var {
        imageFile
      } = this.data
      var that = this
      wx.openSetting({
        success(settingData) {
          if (settingData.authSetting['scope.writePhotosAlbum']) {
            that.saveImage(imageFile)
            // that.triggerEvent('myevent', {
            //   'permissionSetting': {
            //   }
            // })
            that.setData({
              'permissionSetting.save': true,
              'permissionSetting.setingOn': false
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '获取权限失败,图片不能保存',
            })
          }
        }
      })
    },
    saveImage() {
      saveImageToPhotosAlbum({
        filePath: this.data.imageFile
      }, this).then(() => {
        wx.showToast({
          icon: 'none',
          title: '分享图片已保存至相册',
          duration: 2000,
        })
      }).catch(() => {})
    },
    draw() {
      var {
        avatarUrl,
        nickName
      } = this.data.authorization
      var that = this
      var datas = this.data.permissionSetting.data
      if (datas.length > 6) {
        datas = data.slice(0, 6)
      }
      wx.showLoading({
        title: '加载图片中',
      })
      var forEachArrs = this.forEachArr()
    
      var promiseArr = datas.map(async function(req) { // 商品图片
        return getImageInfo(req.goods_cover)
      });
      var avatarPromise = getImageInfo(avatarUrl)
      promiseArr.push(forEachArrs) //商品文字

      var typeShare = this.data.permissionSetting.typeShare;

      var shareType;
      if (typeShare == 2) {
        shareType = `mid=${getApp().globalData.member_id}&type=2&gid=${datas[0].goods_id}`
      } else {
        shareType = `mid=${getApp().globalData.member_id}&type=1`
      }
      promiseArr.push(util.utilUrl(shareType)) //EWM
      promiseArr.push(avatarPromise) //头像
      Promise.all(promiseArr).then((resData) => {
        var ctx = wx.createCanvasContext('share', this)
        //这是头像
        var imageW = 106
        ctx.fillStyle = "#FFFFFF";
        ctx.fillRect(0, 0, this.data.windowWidth, this.data.windowHeight);
        ctx.fill()
        ctx.save();
        ctx.beginPath();
        var circelLocaltion = 20 * rate + rate * imageW / 2
        ctx.arc(circelLocaltion, circelLocaltion, rate * imageW / 2, 0, 2 * Math.PI, false)
        ctx.clip()
        ctx.drawImage(
          resData[resData.length - 1].path,
          20 * rate,
          20 * rate,
          rate * imageW,
          rate * imageW,
        )
        ctx.restore()
        // 这是微信名
        ctx.setFontSize(rate * 30)
        ctx.setFillStyle('#333333')
        nickName.length > 8 ? nickName = nickName.slice(0, 7) + "..." : ''
        ctx.fillText(
          nickName,
          rate * 146,
          rate * 50,
        )
        //这是名字下边得文字
        ctx.setFontSize(rate * 24)
        ctx.setFillStyle('#999999')
        ctx.fillText(
          '精挑选细选的爆款好货，跟着我',
          rate * 146,
          rate * 94,
        )
        ctx.fillText(
          '买准没错',
          rate * 146,
          rate * 134,
        )
        //商品图文
        datas.forEach((item, index) => {
          var namejisuP = parseInt(index / 3) * item.wh.toptInterval * rate
          var nameJisuan = (index - parseInt(index / 3) * 3) * item.wh.leftInterval * rate
          var nameIntervalTop = rate * item.wh.marginLeft + nameJisuan

          ctx.drawImage(
            resData[index].path,
            rate * item.wh.marginLeft + nameJisuan,
            rate * item.wh.marginTop + namejisuP,
            rate * item.wh.imageItemW,
            rate * item.wh.imageItemW,
          )
          item.goods_name.forEach((items, indexs) => {
            ctx.setFontSize(rate * item.wh.fontSize)
            ctx.setFillStyle('#333333')
            ctx.fillText(
              items,
              nameIntervalTop,
              rate * item.wh.fontTop + rate * indexs * 25 + namejisuP,
            )
          })
          ctx.setFontSize(rate * (item.wh.fontSize + 3))
          ctx.setFillStyle('#333333')
          ctx.fillText(
            '¥' + item.low_goods_price,
            nameIntervalTop,
            rate * item.wh.moneyTop + namejisuP,
          )
          // if (item.wh.zhuan) {
          //   ctx.setFontSize(rate * (item.wh.fontSize - 5))
          //   ctx.setFillStyle('#ff3b30')
          //   ctx.fillText(
          //     '赚' + item.commission,
          //     rate * item.wh.makeMoney + nameJisuan,
          //     rate * item.wh.moneyTop + namejisuP,
          //   )
          // }
        })
        // EWM
        ctx.drawImage(
          resData[resData.length - 2].path,
          (this.data.windowWidth - rate * 178) / 2,
          682 * rate,
          rate * 178,
          rate * 178,
        )
        //这是EWM上边得文字
        ctx.setFontSize(rate * 30)
        ctx.setFillStyle('#333333')
        ctx.fillText(
          '精挑选细选的爆款好货',
          rate * 63,
          rate * 598,
        )
        ctx.fillText(
          '跟着我买准没错',
          rate * 221,
          rate * 646,
        )

        // 画图
        ctx.draw(true, () => {
          canvasToTempFilePath({
            canvasId: 'share',
          }, this).then(
            ({
              tempFilePath
            }) => {

              this.setData({
                imageFile: tempFilePath
              })
            }

          )
        })
        wx.hideLoading()
        return '王萌'
      }).then(res => {})

    },

  }
})